<template>
  <GlobalDrawer
    v-model="visible"
    :title="drawerTitle"
    :size="size"
    :before-close="handleBeforeClose"
    @confirm="handleConfirm"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="chance-form"
      label-position="top"
    >
      <el-form-item label="机会名称" prop="title">
        <el-input v-model="formData.title" placeholder="请输入机会名称" :disabled="isView" />
      </el-form-item>

      <el-form-item label="预计签单金额" prop="expected_order_amount">
        <el-input
          v-model.number="formData.expected_order_amount"
          placeholder="请输入预计签单金额"
          :disabled="isView"
        >
          <template #append>元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="发现时间" prop="discovery_time">
        <el-date-picker
          v-model="formData.discovery_time"
          type="datetime"
          placeholder="请选择发现时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          :clearable="false"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="预计成交时间" prop="expected_time">
        <el-date-picker
          v-model="formData.expected_time"
          type="datetime"
          placeholder="请选择预计成交时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          :clearable="true"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="阶段" prop="stage">
        <el-select
          v-model="formData.stage"
          placeholder="请选择阶段"
          :disabled="isView"
          style="width: 100%"
        >
          <el-option
            v-for="stage in stageOptions"
            :key="stage.id"
            :label="stage.title"
            :value="stage.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="内容描述" prop="content">
        <el-input
          v-model="formData.content"
          type="textarea"
          :rows="4"
          placeholder="请输入内容描述"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item v-if="mode === 'view'">
        <div class="chance-info">
          <div class="info-item">
            <span class="label">负责人：</span>
            <span class="value">{{ formData.admin_name || '未知' }}</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">
              {{ formData.create_time ? formatDateTime(formData.create_time) : '未知' }}
            </span>
          </div>
        </div>
      </el-form-item>
    </el-form>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch, onMounted } from 'vue'
  import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
  import { GlobalDrawer } from '@/components/common'
  import request from '@/utils/request'
  import { ApiResponse } from '@/types/api'
  import { formatDate, formatDateTime } from '@/utils/format'
  import { customerApi } from '@/api/customer'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    customerId: {
      type: [Number, String],
      required: true,
    },
    chanceId: {
      type: [Number, String],
      default: '',
    },
    mode: {
      type: String,
      default: 'add', // 'add', 'edit', 'view'
      validator: (value: string) => ['add', 'edit', 'view'].includes(value),
    },
    size: {
      type: String,
      default: '80%',
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  // 表单引用
  const formRef = ref<FormInstance>()

  // 阶段选项数据（添加缓存）
  const stageOptions = ref<any[]>([])
  const stageOptionsLoaded = ref(false)

  // 抽屉可见状态
  const visible = computed({
    get: () => props.modelValue,
    set: val => emit('update:modelValue', val),
  })

  // 是否是查看模式
  const isView = computed(() => props.mode === 'view')

  // 抽屉标题
  const drawerTitle = computed(() => {
    switch (props.mode) {
      case 'add':
        return '新增销售机会'
      case 'edit':
        return '编辑销售机会'
      case 'view':
        return '查看销售机会'
      default:
        return '销售机会'
    }
  })

  // 提交状态
  const submitting = ref(false)

  // 表单数据
  const formData = reactive({
    id: '',
    customer_id: '',
    title: '',
    expected_order_amount: 0,
    discovery_time: '',
    expected_time: '',
    stage: 1,
    content: '',
    admin_id: 0,
    admin_name: '',
    create_time: '',
  })

  // 表单验证规则
  const rules = {
    title: [{ required: true, message: '请输入机会名称', trigger: 'blur' }],
    expected_order_amount: [
      { required: true, message: '请输入预计金额', trigger: 'blur' },
      { type: 'number', message: '请输入有效的数字', trigger: 'blur' },
    ],
    discovery_time: [{ required: true, message: '请选择发现时间', trigger: 'change' }],
    stage: [{ required: true, message: '请选择阶段', trigger: 'change' }],
  }

  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }

    formData.id = ''
    formData.customer_id = props.customerId.toString()
    formData.title = ''
    formData.expected_order_amount = 0

    // 使用当前时间的格式化字符串作为默认值
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hour = String(now.getHours()).padStart(2, '0')
    const minute = String(now.getMinutes()).padStart(2, '0')
    const second = String(now.getSeconds()).padStart(2, '0')

    formData.discovery_time = `${year}-${month}-${day} ${hour}:${minute}:${second}`
    formData.expected_time = ''
    formData.stage = 1
    formData.content = ''
    formData.admin_id = 0
    formData.admin_name = ''
    formData.create_time = ''
  }

  // 获取阶段选项数据（带缓存）
  const getStageOptions = async () => {
    // 如果已经加载过，直接返回缓存数据
    if (stageOptionsLoaded.value && stageOptions.value.length > 0) {
      return
    }

    try {
      const response: ApiResponse<any[]> = await customerApi.getChanceStageOptions()
      if (response.code === 0 && Array.isArray(response.data)) {
        stageOptions.value = response.data
        stageOptionsLoaded.value = true
      } else {
        // 接口失败时使用默认值作为后备
        stageOptions.value = [
          { id: 1, title: '初步接触' },
          { id: 2, title: '需求分析' },
          { id: 3, title: '方案报价' },
          { id: 4, title: '商务谈判' },
          { id: 5, title: '成交' },
          { id: 6, title: '失败' },
        ]
      }
    } catch (error) {
      // 网络错误时使用默认值
      stageOptions.value = [
        { id: 1, title: '初步接触' },
        { id: 2, title: '需求分析' },
        { id: 3, title: '方案报价' },
        { id: 4, title: '商务谈判' },
        { id: 5, title: '成交' },
        { id: 6, title: '失败' },
      ]
    }
  }

  // 监听chanceId变化，加载详情
  watch(
    () => props.chanceId,
    newVal => {
      if (newVal && (props.mode === 'edit' || props.mode === 'view')) {
        loadChanceDetail(newVal)
      }
    },
    { immediate: true }
  )

  // 监听mode变化，重置表单
  watch(
    () => props.mode,
    () => {
      resetForm()
      // 切换模式时重新加载阶段选项数据，但只有在还没加载过或抽屉可见时才加载
      if (!stageOptionsLoaded.value || visible.value) {
        getStageOptions()
      }
    },
    { immediate: true }
  )

  // 监听customerId变化，更新表单数据
  watch(
    () => props.customerId,
    newVal => {
      if (newVal) {
        formData.customer_id = newVal.toString()
      }
    },
    { immediate: true }
  )

  // 加载销售机会详情
  const loadChanceDetail = async (chanceId: string | number) => {
    try {
      // 使用正确的ApiResponse类型
      const response: ApiResponse<any> = await request({
        url: '/api/customer/chance/view',
        method: 'get',
        params: { id: chanceId },
      })

      if (response && response.code === 0 && response.data) {
        // 填充表单数据
        formData.id = response.data.id
        formData.customer_id = response.data.customer_id || response.data.cid
        formData.title = response.data.title
        formData.expected_order_amount = response.data.expected_order_amount || 0

        // 将秒级时间戳转换为日期字符串
        const discoveryTime = Number(response.data.discovery_time)
        const expectedTime = Number(response.data.expected_time)

        if (discoveryTime) {
          const discoveryDate = new Date(discoveryTime * 1000) // 秒转毫秒
          const year = discoveryDate.getFullYear()
          const month = String(discoveryDate.getMonth() + 1).padStart(2, '0')
          const day = String(discoveryDate.getDate()).padStart(2, '0')
          const hour = String(discoveryDate.getHours()).padStart(2, '0')
          const minute = String(discoveryDate.getMinutes()).padStart(2, '0')
          const second = String(discoveryDate.getSeconds()).padStart(2, '0')
          formData.discovery_time = `${year}-${month}-${day} ${hour}:${minute}:${second}`
        } else {
          formData.discovery_time = ''
        }

        if (expectedTime) {
          const expectedDate = new Date(expectedTime * 1000) // 秒转毫秒
          const year = expectedDate.getFullYear()
          const month = String(expectedDate.getMonth() + 1).padStart(2, '0')
          const day = String(expectedDate.getDate()).padStart(2, '0')
          const hour = String(expectedDate.getHours()).padStart(2, '0')
          const minute = String(expectedDate.getMinutes()).padStart(2, '0')
          const second = String(expectedDate.getSeconds()).padStart(2, '0')
          formData.expected_time = `${year}-${month}-${day} ${hour}:${minute}:${second}`
        } else {
          formData.expected_time = ''
        }

        formData.stage = response.data.stage || 1
        formData.content = response.data.content || ''
        formData.admin_id = response.data.admin_id
        formData.admin_name = response.data.admin_name
        formData.create_time = response.data.create_time
      } else {
        ElMessage.error(response?.msg || '获取销售机会详情失败')
        closeDrawer()
      }
    } catch (error) {
      ElMessage.error({ message: '获取销售机会详情失败' })
      closeDrawer()
    }
  }

  // 提交表单
  const handleConfirm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async valid => {
      if (!valid) return

      submitting.value = true

      try {
        // 将日期字符串转换为秒级时间戳并确保是整数
        let discoveryTimeStamp = 0
        let expectedTimeStamp = 0

        if (formData.discovery_time) {
          const discoveryDate = new Date(formData.discovery_time)
          discoveryTimeStamp = Math.floor(discoveryDate.getTime() / 1000)
        }

        if (formData.expected_time) {
          const expectedDate = new Date(formData.expected_time)
          expectedTimeStamp = Math.floor(expectedDate.getTime() / 1000)
        }

        // 转换时间戳格式，确保发送到后端的是秒级时间戳
        let submitData: any = {
          customer_id: props.customerId,
          title: formData.title,
          expected_order_amount: formData.expected_order_amount,
          discovery_time: discoveryTimeStamp,
          expected_order_date: expectedTimeStamp,
          stage: formData.stage,
          content: formData.content,
        }

        // 编辑模式需要添加id
        if (props.mode === 'edit') {
          submitData.id = formData.id

          // 使用customerApi.editCustomerChance
          try {
            const response = await customerApi.editCustomerChance(submitData)

            if (response && response.code === 0) {
              ElMessage.success('编辑机会线索成功')
              emit('success')
              closeDrawer()
            } else {
              ElMessage.error(response?.msg || '编辑机会线索失败')
            }
          } catch (error) {
            ElMessage.error('编辑机会线索失败')
          }
        } else {
          // 新增模式 - 使用customerApi.addCustomerChance
          try {
            const response = await customerApi.addCustomerChance(submitData)

            if (response && response.code === 0) {
              ElMessage.success('添加机会线索成功')
              emit('success')
              closeDrawer()
            } else {
              ElMessage.error(response?.msg || '添加机会线索失败')
            }
          } catch (error) {
            ElMessage.error('添加机会线索失败')
          }
        }
      } catch (error) {
        ElMessage.error(props.mode === 'add' ? '添加失败' : '编辑失败')
      } finally {
        submitting.value = false
      }
    })
  }

  // 关闭抽屉前的处理
  const handleBeforeClose = () => {
    if (props.mode === 'view') {
      return true
    }

    // 检查表单是否有改动
    if (formData.title || formData.content) {
      return ElMessageBox.confirm('确定要关闭吗？未保存的内容将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return true
        })
        .catch(() => {
          return false
        })
    } else {
      return true
    }
  }

  // 关闭抽屉
  const closeDrawer = () => {
    visible.value = false
  }

  // 初始化
  onMounted(async () => {
    resetForm()
    // 预加载阶段选项数据，确保在打开抽屉时已加载完成
    await getStageOptions()
  })
</script>

<style scoped>
  .chance-form {
    padding: 20px;
  }

  /* 覆盖GlobalDrawer的页脚样式，保持一致性 */
  :deep(.drawer-footer) {
    display: flex;
    justify-content: flex-end;
    padding: 0 20px 20px;
  }

  .chance-info {
    background-color: #f8f9fa;
    padding: 10px 15px;
    border-radius: 4px;
    margin-top: 10px;
  }

  .info-item {
    display: flex;
    margin-bottom: 8px;
  }

  .info-item .label {
    font-weight: 500;
    color: #606266;
    width: 90px;
  }

  .info-item .value {
    color: #303133;
    flex: 1;
  }
</style>
